<template>
  <div v-loading="loading">

    <el-button
      v-if="moduleNameOptions&&activePageForm&&activePageForm.activeModuleIndex!=null &&(!moduleNameOptions[activePageForm.modules[activePageForm.activeModuleIndex].type].maxSize
        ||couponList.length<moduleNameOptions[activePageForm.modules[activePageForm.activeModuleIndex].type].maxSize)"
      type="primary"
      size="small"
      round
      @click="addModule"
    >新增内容
    </el-button>
    <div
      v-if="activePageForm.modules[activePageForm.activeModuleIndex].modules.length == 0"
      class="empty-tips"
    >
      未配置数据
    </div>

    <!-- 站内链接 -->
    <!-- <template v-else> -->
    <template>
      <ul class="shelf-list-container">
        <draggable :list="couponList" :options="{ filter: '.undrag' }" @sort="modulesDragSort">
          <li v-for="(item, index) in couponList" :key="item.id" class="shelf-container">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <div class="flexRBC">
                  <div>
                    <span
                      v-if="item.title"
                      style="fontWeight: bold; line-height: 32px"
                    > {{ index + 1 }}.&nbsp;&nbsp;{{ item.title }}</span>
                    <span
                      v-if="item.subTitle"
                      style="font-size: 14px; line-height: 32px"
                    > &nbsp;&nbsp;{{ item.subTitle }}</span>
                    <!--                    <div v-else-if="item.bg" class="flexRSC">-->
                    <!--                      <span style="fontWeight: bold; line-height: 32px"> {{ index + 1
            }}.&nbsp;&nbsp;</span>-->
                    <!--                      <el-image :src="fileBaseUrl + item.bg" class="title-bg"/>-->
                    <!--                    </div>-->
                    <!--                    <span v-else style="fontWeight: bold; line-height: 32px"> {{ index + 1
            }}. </span>-->
                  </div>
                  <div>
                    <el-button size="mini" type="primary" round @click="editModule(item, index)">编辑</el-button>
                    <el-button size="mini" type="danger" round @click="delModule(item, index)">删除</el-button>
                    <el-button v-if="couponList.length > 1" size="mini" round>拖拽排序</el-button>
                  </div>
                </div>
              </div>
              <el-table
                :data="item.couponList"
                style="width: 100%"
                empty-text="暂无数据"
                border
                stripe
                class="coupon-container"
                size="small"
                max-height="400"
              >
                <el-table-column prop="couponId" label="批次号" />
                <el-table-column prop="couponName" label="卡/券名称" />
                <el-table-column prop="couponType" label="卡券类型">
                  <template slot-scope="scope">
                    {{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] || "--" }}
                  </template>
                </el-table-column>
              </el-table>
              <!--              <ul v-if="item.type == 0 && item.goodsList" ref="shelfGoodsList " class="goods-list">-->
              <!--                <draggable :list="item.goodsList" :options="{ filter: '.undrag' }" @sort="goodsDragSort(item)">-->
              <!--                  <li v-for="(subItem, subIndex) in item.goodsList" :key="subIndex" class="cell-item flexRBC">-->
              <!--                    <div class="flexRSC">-->
              <!--                      <img v-if="subItem.coverImg" :src="fileBaseUrl + subItem.coverImg" class="cover-img">-->
              <!--                      <div>-->
              <!--                        <div class="goods-name">{{ subItem.title }}</div>-->
              <!--                        <div>{{ subItem.category.join(" > ") }}</div>-->
              <!--                      </div>-->
              <!--                    </div>-->
              <!--                    <div>-->
              <!--                      <el-button v-if="item.goodsList.length > 1" icon="el-icon-sort" size="small" round>拖拽排序-->
              <!--                      </el-button>-->
              <!--                    </div>-->
              <!--                  </li>-->
              <!--                </draggable>-->
              <!--              </ul>-->
              <!--              <ul v-if="item.type == 1 && item.categoryList" class="category-list">-->
              <!--                <li v-for="subItem in item.categoryList" :key="subItem.id" class="cell-item">-->
              <!--                  {{ subItem.names.join(" > ") }}-->
              <!--                </li>-->
              <!--              </ul>-->
            </el-card>
          </li>
        </draggable>
      </ul>
    </template>

    <!-- 组件 -->
    <DialogCoupon ref="dialogCoupon" />
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import wxaBuildConfig from '@/views/wxaBuildModule/config'
import DialogCoupon from './DialogCoupon'
import { mapGetters } from 'vuex'
import { getCardCouponByIds } from '@/views/cardsAndOffer/api/coupon'

export default {
  components: {
    DialogCoupon,
    draggable
  },

  data() {
    return {
      // 配置
      moduleNameOptions: null,
      // 状态
      loading: false,
      // 数据
      classifyCode: 'DEFAULT',
      couponIds: [],
      couponList: []
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'activePageForm'])
  },
  watch: {
    'activePageForm.activeModuleIndex'() {
      this.fetchData()
    }
  },
  created() {
  },
  mounted() {
    this.moduleNameOptions = wxaBuildConfig[this.classifyCode].moduleName
    this.fetchData()
  },
  methods: {
    /**
     * 数据组
     */
    // 获取所有shelfIds
    fetchData() {
      let couponIds = []
      this.couponList = []
      const modules = this.activePageForm.modules[
        this.activePageForm.activeModuleIndex
      ].modules
      modules.forEach((v) => {
        if (v.biz && v.biz.params && v.biz.params.couponIds) {
          couponIds = couponIds.concat(v.biz.params.couponIds)
        }
      })
      if (couponIds.length) {
        this.getCoupon(couponIds)
      }
    },

    // 获取券列表
    getCoupon(couponIds) {
      this.loading = true
      getCardCouponByIds({ prototypeId: couponIds })
        .then((res) => {
          const modules = this.activePageForm.modules[
            this.activePageForm.activeModuleIndex
          ].modules
          const couponList = res.data || []
          const couponMap = res.data || []
          couponList.forEach(v => {
            if (v.detail) {
              couponMap[v.detail.prototype.id] = {
                couponId: v.detail.prototype.id,
                couponName: v.type === 'card' ? v.detail.prototype.cardName : v.detail.prototype.couponName,
                couponType: v.type === 'card' ? v.detail.prototype.cardType : v.detail.prototype.couponType
              }
            }
          })
          modules.forEach((moduleItem) => {
            const couponItem = {
              title: moduleItem.title,
              pic: moduleItem.pic,
              subTitle: moduleItem.subTitle,
              couponList: [],
              couponIds: []
            }
            moduleItem.biz.params.couponIds.forEach(v => {
              if (couponMap[v]) {
                couponItem.couponList.push(couponMap[v])
                couponItem.couponIds.push(v)
              }
            })
            this.couponList.push(couponItem)
          })
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 按钮组
     */
    // 新增
    addModule() {
      this.$refs.dialogCoupon.open({ mode: 'add' }).then((res) => {
        this.couponList = this.couponList.concat(res)
        console.log(this.couponList)
        this.activePageForm.modules[
          this.activePageForm.activeModuleIndex
        ].modules.push({
          bg: '',
          biz: {
            params: { couponIds: res.couponIds },
            type: 'COUPON'
          },
          color: '',
          content: '',
          dump: {
            appId: '',
            feature: '',
            featureParams: '',
            insidePage: '',
            insideParams: '',
            path: '',
            type: '',
            url: ''
          },
          modules: [],
          pic: res.pic,
          ranking: 0,
          style: '',
          subTitle: res.subTitle,
          subType: '',
          title: res.title,
          type: this.activePageForm.modules[
            this.activePageForm.activeModuleIndex
          ].type
        })
      })
    },

    // 编辑货架
    editModule(row, index) {
      this.$refs.dialogCoupon.open({ mode: 'edit', row }).then((res) => {
        this.couponList.splice(index, 1, res)
        this.activePageForm.modules[
          this.activePageForm.activeModuleIndex
        ].modules[index].title = res.title
        this.activePageForm.modules[
          this.activePageForm.activeModuleIndex
        ].modules[index].subTitle = res.subTitle
        this.activePageForm.modules[
          this.activePageForm.activeModuleIndex
        ].modules[index].pic = res.pic
        this.activePageForm.modules[
          this.activePageForm.activeModuleIndex
        ].modules[index].biz.params.couponIds = res.couponIds
      })
    },

    // 删除
    delModule(item, index) {
      this.activePageForm.modules[
        this.activePageForm.activeModuleIndex
      ].modules.splice(index, 1)
      this.couponList.splice(index, 1)
    },

    // 货架拖拽结束
    modulesDragSort(val) {
      // const newShelfIds = []
      const modules = this.activePageForm.modules[
        this.activePageForm.activeModuleIndex
      ].modules
      const newModules = []
      this.couponList.forEach((v) => {
        modules.some((moduleItem) => {
          if (JSON.stringify(v.couponIds) === JSON.stringify(moduleItem.biz.params.couponIds)) {
            newModules.push(moduleItem)
            return true
          }
        })
      })
      this.activePageForm.modules[
        this.activePageForm.activeModuleIndex
      ].modules = newModules
    },

    // 商品拖拽结束
    goodsDragSort(val) {
      this.loading = true
      saveShelf(val)
        .then((res) => {
        })
        .catch((err) => {
        })
        .finally(() => {
          this.loading = false
        })
    }

    /**
     * 状态组
     */

    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 覆盖样式 */
::v-deep {
  .el-card__body {
    padding: 10px 20px;
  }

  .el-card__header {
    padding: 10px 20px;
  }
}

/* 无数据 */
.empty-tips {
  margin-top: 100px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 货架 */
.shelf-container {
  margin-top: 10px;
  cursor: move;

  .title-bg {
    width: 188px;
    height: 33px;
  }
}

/* 排序 */
.el-icon-rank {
  cursor: pointer;
  font-size: 20px;
  margin-right: 10px;
}
</style>
